# -*- coding:utf-8 -*-
# author: lawaiter
# time: 2020/6/24
# brief: 这是继承QtMUltimedia中QMediaplayer自定义类逻辑

import os
import json
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist, QMediaContent
from PyQt5.QtCore import QUrl
from utils import SongInfo


class Myplayer():

    """自定义的播放器类"""

    def __init__(self):
        self.allSong = []
        # 读取配置文件中默认的音乐文件根目录
        self.songsDir = self.playSettingExistOrNot()
        self.getSongs()
        # 创建播放器
        self.player = QMediaPlayer()
        # 创建播放器列表
        self.playList = QMediaPlaylist()
        # 设置循环播放
        self.playList.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        for i in self.allSong:
            # 把所有歌曲添加到列表中
            self.playList.addMedia(QMediaContent(QUrl.fromLocalFile(i)))
        # 将当前的播放列表加载到播放器
        self.player.setPlaylist(self.playList)
        print(self.playList.CurrentItemInLoop)
        self.songInfo = self.GetSongInfo()

    def playOrStop(self):

        """播放暂停按钮控制"""

        if self.player.state() == 1:
            self.player.pause()
            self.player.setVolume(50.0)
            # self.statusbar.showMessage('暂停')
            # self.startStop.setText('播放')
        elif self.player.state() == 2:
            self.player.play()
            self.player.setVolume(50.0)
            self.statusShow()
            # self.startStop.setText('暂停')

    def statusShow(self):

        """显示歌曲名"""

        self.songInfo = self.GetSongInfo()
        # self.statusbar.showMessage(songInfo.title)
        return self.songInfo

    def nextSong(self):

        """下一首"""

        self.playList.next()
        self.statusShow()

    def preSong(self):

        """上一首"""

        self.playList.previous()
        self.statusShow()

    def GetSongInfo(self):

        """获取歌曲信息"""

        # 获取当前播放曲目路径
        path = self.player.currentMedia().canonicalUrl().path()[1:]
        if path[-3:] == 'mp3' or path[-3:] == 'MP3':
            info = SongInfo.GetMp3Info(path)
        elif path[-4:] == 'FLAC' or path[-4:] == 'flac':
            info = SongInfo.GetFlacInfo(path)
        else:
            info = None
        return info

    def getSongs(self):
 
        """获取文件夹内所有的歌曲"""

        self.allSong = []
        for root, dirs, files in os.walk(self.songsDir):
            for file in files:
                # 如果是MP3文件则加入至列表
                if file[-3:] == 'mp3' or file[-3:] == 'MP3' \
                or file[-4:] == 'FLAC' or file[-4:] == 'flac':
                    self.allSong.append(os.path.join(root, file))
        return self.allSong

    def doubleClickPlaySong(self, index):
        
        """
        双击后播放
        :param index: 索引号 tableView.currentIndex().row()
        """

        self.playList.setCurrentIndex(index)

    def addSongsToPlaylist(self):

        """添加歌曲到播放列表"""

        self.getSongs()
        try:
            print(self.playList.mediaCount())
            self.playList.clear()
            if self.allSong:
                for i in self.allSong:
                    self.playList.addMedia(QMediaContent(QUrl.fromLocalFile(i)))
                self.player.setPlaylist(self.playList)
        except:
            pass
        else:
            self.player.setPlaylist(self.playList)

    def playSettingExistOrNot(self):

        """
        确定是否存在配置文件，配置文件中是否存在播放目录
        """

        try:
            with open('./conf/playSetting.json', 'r') as f:
                value = json.load(f)['DIR_URL']
        except:
            value = ''
        return value




if __name__ == "__main__":
    player1 = Myplayer()
    print(player1.getSongs())
    print(player1.player.setVolume(80.0))
    print(player1.playList)
    player1.player.play()